import { App, FunctionPlugin, ObjectPlugin } from 'vue'
import { ErrorName } from '@/error/ErrorName.ts'
import { ElMessage } from 'element-plus'
import { ApiError } from '@/error/ApiError.ts'
import { ComponentPublicInstance } from 'vue'

//全局异常处理
const errorHandler = (error: unknown, vm: ComponentPublicInstance | null, info: string) => {
  if (error instanceof Error) {
    switch (error.name) {
      case ErrorName.ValidateError:
        ElMessage.error(error.message)
        break
      case ErrorName.ApiError:
        ElMessage.error(error.message)
        break
      case ErrorName.AxiosError: {
        const apiError = error as ApiError
        console.log('接口调用异常', apiError.code, apiError.message)
        ElMessage.error(error.message)
        break
      }
      default:
        console.error('Global error handler:', error, vm, info)
    }
  } else {
    console.log('global info:', error, vm, info)
  }
}

let errorHandlerPlugin: FunctionPlugin | ObjectPlugin = {
  install: (app: App) => {
    app.config.errorHandler = errorHandler
    window.onerror = (message, source, line, column, error) => {
      //还没有触发过这个方法
      console.log('window.onerror', message, source, line, column, error)
      errorHandler(error, null, '全局捕获错误')
    }
    window.addEventListener('unhandledrejection', event => {
      errorHandler(event.reason, null, '全局捕获未处理的Promise异常')
    })
  },
}

export default errorHandlerPlugin
